import { defineStore } from "pinia"

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: []
  }),
  actions: {
    addCart(data) {
      this.cartList.push(data)
    },
    setCart(skuId, data) {
      // 根据skuId查找商品并更新数据
      const index = this.cartList.findIndex(item => item.skuId === skuId)
      if (index !== -1) {
        // 合并更新数据，保留未被更新的字段
        this.cartList[index] = { ...this.cartList[index], ...data }
      }
    },
    removeCart(skuId) {
      this.cartList = this.cartList.filter((item) => item.skuId !== skuId)
    },
    clearCart() {
      // 清空购物车列表
      this.cartList = []
    }
  },
  getters: {
    getCartList() {
      return this.cartList
    },
    getTotal() {
      return this.cartList.reduce((pre, cur) => pre +  cur.num , 0)
    },
    getSelectTotal() {
      return this.cartList.reduce((pre, cur) => pre + (cur.selected ? cur.num : 0), 0)
    },
    // 共计多少钱
    getTotalPrice() {
      return this.cartList.reduce((pre, cur) =>pre +cur.num * cur.price , 0)
    },
    // 共计多少钱
    getSelectTotalPrice() {
      return this.cartList.reduce((pre, cur) =>pre + (cur.selected ? cur.num * cur.price : 0), 0)
    }
  },

  persist: true


})
